<?php

namespace app\admin\middleware\common;

use app\admin\service\admin\UserService;
use app\admin\service\common\AuthCheckService;
use app\admin\service\common\RSAEncryptService;
use app\admin\service\common\token\TokenServiceFactory;
use app\admin\service\common\UserActivityService;
use app\common\Constants;
use app\common\ErrorCode;
use app\common\exception\BusinessException;
use app\common\facade\Principal;
use app\common\helper\HttpHelper;
use think\facade\Log;
use think\helper\Str;
use think\Request;
use think\Response;

class CheckAuth
{

    protected $tokenService;

    // 依赖注入Token服务和用户服务
    public function __construct(
        protected UserService $userService
    ) {
        $this->tokenService = TokenServiceFactory::create();
    }

    public function handle(Request $request, \Closure $next): Response
    {
        if (!file_exists(root_path() . 'install.lock')) {
            return $next($request);
        }

        // 记录日志
        if (app()->isDebug()) {
            $url = request()->url();
            $params = request()->param();
            $pathinfo = $request->pathinfo();

            trace("\r\n");
            trace('-------------------------Start---------------------------', 'Debug');
            trace($url, "URL");
            trace($pathinfo, "PathInfo");
            trace($params, 'Debug');
        }

        // 解密指定字段数据
        $postData = $request->post();
        $postData = RSAEncryptService::decrypt($postData);
        $request = $request->withPost($postData);


        // 跳过白名单
        $except = array_map('strtolower', config('rds.except_list'));
        $route = strtolower($request->pathinfo());
        trace($route, '检查白名单路由');
        if (in_array($route, $except) || empty($route)) {
            trace('The current URL is on the whitelist', 'debug');
            return $next($request);
        }

        // 验证 Token
        $paylod = $this->tokenService->validateToken(HttpHelper::getBearerToken());
        $token_info = $paylod['data'];
        $request->userInfo = $this->userService->getPrincipalInfo($token_info->id);


        return $next($request);
    }
}
